package android.medicalcloud.com.yiapp.yilian.utils.net;


import android.medicalcloud.com.yiapp.base.cach.PreferceManager;
import android.medicalcloud.com.yiapp.base.net.lisener.NetCallback;
import android.medicalcloud.com.yiapp.base.net.lisener.ViewNetCallBack;
import android.medicalcloud.com.yiapp.base.utils.Logger;
import android.medicalcloud.com.yiapp.base.utils.MD5Util;
import android.medicalcloud.com.yiapp.base.utils.MapUtils;
import android.medicalcloud.com.yiapp.base.utils.StringTools;
import android.medicalcloud.com.yiapp.yilian.application.YilianAppcation;
import android.medicalcloud.com.yiapp.yilian.configer.enums.HttpConfig;
import android.medicalcloud.com.yiapp.yilian.configer.xml.HttpManager;
import android.medicalcloud.com.yiapp.yilian.model.HttpConfigBean;
import android.medicalcloud.com.yiapp.yilian.ui.view.dialog.LoadDialog;
import android.medicalcloud.com.yiapp.yilian.utils.android.GsonTool;
import android.medicalcloud.com.yiapp.yilian.utils.android.IntentTool;
import android.medicalcloud.com.yiapp.yilian.utils.android.JsonTool;
import android.medicalcloud.com.yiapp.yilian.utils.android.ToastTool;
import android.util.Log;

import com.tencent.imcore.IFileTrans;

import org.json.JSONArray;
import org.json.JSONObject;
import java.io.Serializable;
import java.util.Map;

/**
 * 对底层接口的 对接
 */
public class BaseNetImpl implements NetCallback {

    ViewNetCallBack listener;
    Class entityClass;
    HttpConfigBean config;
    Map<String, Object> param;
    HttpConfig con;

    public BaseNetImpl(ViewNetCallBack listener, Class entityClass, HttpConfig config) {
        this.listener = listener;
        this.entityClass = entityClass;
        this.config = HttpManager.getInstance().getConifgById(config);
        con = config;

    }

    public void setParam(Map<String, Object> param) {
        this.param = param;
    }



    private void paseReslut(String jsonstring){
        Logger.e("jsonstring    "+jsonstring);
        try {
            String code  = JsonTool.getString(jsonstring, "retCode");
            if((!StringTools.isNullOrEmpty(code))&&code.equals("0")){

                JSONArray error= JsonTool.getJsonArray(jsonstring,"errors");
                if (error!=null&&error.length()>0){
                    for (int i=0;i<error.length();i++){
                        JSONObject jo = error.getJSONObject(i);
                        String logicCode = JsonTool.getString(jo.toString(),"code");
                        String message = JsonTool.getString(jo.toString(),"message");
                        try {
                            //config.getId()!=HttpConfig.bindPush.getType()&&
                            if (!YilianAppcation.instance.currentActivity.getClass().getName().contains("Login")){
                                IntentTool.loginClearTop(YilianAppcation.instance.getApplicationContext());
                            }
                        }catch (Exception e){

                        }
                        if (config.isShowNotify()){

                            if (!StringTools.isNullOrEmpty(message)){
                                ToastTool.show(message);
                            }
                        }


                    }
                }

                String url = MapUtils.map2UrlParams(config.getActioin(), param);
                Logger.e(url + "baseResult=" + jsonstring);
                if (config.isCach()) {
                    url = MapUtils.map2UrlParams(config.getActioin(), param);
                    PreferceManager.getInsance().saveValueBYkey(MD5Util.string2MD5(url), jsonstring);
                }
                String data = JsonTool.getString(jsonstring,"data");
                try {
                    listener.onData((Serializable) GsonTool.jsonToEntity(data, entityClass), config.getId(), true, data);
                } catch (Exception e) {
                    Logger.e(e.getLocalizedMessage(),e);
                    listener.onData((Serializable) GsonTool.jsonToArrayEntity(data, entityClass), config.getId(), true, data);

                }
                if (config.isShowNotify()){
                    String toast = JsonTool.getString(data,"statusMsg");
                    if (!StringTools.isNullOrEmpty(toast)){
                        ToastTool.show(toast);
                    }
                }

            }else{
                JSONArray error= JsonTool.getJsonArray(jsonstring,"errors");
                if (error!=null&&error.length()>0){
                    for (int i=0;i<error.length();i++){
                        JSONObject jo = error.getJSONObject(i);
                        String logicCode = JsonTool.getString(jo.toString(),"code");
                        String message = JsonTool.getString(jo.toString(),"message");

                        if (logicCode.equals("100")){
                            try {
                                //config.getId()!=HttpConfig.bindPush.getType()&&
                                if (!YilianAppcation.instance.currentActivity.getClass().getName().contains("Login")){
                                    IntentTool.loginClearTop(YilianAppcation.instance.getApplicationContext());
                                }
                            }catch (Exception e){

                            }

                            return;
                        }
                        Logger.e("errorMsg"+config.isShowNotify());
                        Logger.e("errorMsg"+message);
                        if (config.isShowNotify()){

                            if (!StringTools.isNullOrEmpty(message)){
                                ToastTool.show(message);

                            }
                        }


                    }
                }
            }

        } catch (Exception e) {
            listener.onFail(e, con, "");
        }
    }

    @Override
    public void dealReslut(final String jsonstring) {

        paseReslut(jsonstring);

    }

    @Override
    public void dealFailer(Exception e) {
        if (config.isCach()) {
            String url = MapUtils.map2UrlParams(config.getActioin(), param);
            try {
                String jsonstring = PreferceManager.getInsance().getValueBYkey(MD5Util.string2MD5(url));
                Logger.e("-----jsonstring------ERROR---------------"+jsonstring);
                paseReslut(jsonstring);
                return;
            } catch (Exception e1) {

            }
        }
        listener.onFail(e, con, "");
    }

    @Override
    public void onstart() {

        listener.onConnectStart(con);
        String url = MapUtils.map2UrlParams(config.getActioin(), param);
        String jsonstring = PreferceManager.getInsance().getValueBYkey(MD5Util.string2MD5(url));
        if (!StringTools.isNullOrEmpty(jsonstring) && config.isCach()) {
            try {
                JSONObject jsonObject = new JSONObject(jsonstring);
                if (jsonObject.has("data")) {
                    String data = jsonObject.getString("data");
                    try {
                        listener.onData((Serializable) GsonTool.jsonToEntity(data, entityClass), config.getId(), false, jsonstring);
                    } catch (Exception e) {
                        listener.onData((Serializable) GsonTool.jsonToArrayEntity(data, entityClass), config.getId(), false, jsonstring);
                    }
                } else {
                    listener.onData(null, config.getId(), false, jsonstring);
                }
            } catch (Exception e) {

            }
        }

        try {
            if (config.isShowLoadDialog()){
                LoadDialog.createDialog(YilianAppcation.instance.currentActivity).show();
            }
        }catch (Exception e){

        }


    }

    @Override
    public void onEnd() {
        listener.onConnectEnd();

        try {
            if (config.isShowLoadDialog()){
                LoadDialog.createDialog(YilianAppcation.instance.currentActivity).dismiss();
            }
        }catch (Exception e){

        }
    }


}
